from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
import pandas as pd

def perform_regression(df):
    """
    线性回归建模：ROE ~ 净利率 + 资产周转率 + 权益乘数
    """
    results = {}
    for company in df["公司"].unique():
        subset = df[df["公司"] == company]
        X = subset[["净利率", "资产周转率", "权益乘数"]]
        y = subset["ROE"]

        model = LinearRegression().fit(X, y)
        y_pred = model.predict(X)
        r2 = r2_score(y, y_pred)

        results[company] = {
            "coef": dict(zip(X.columns, model.coef_)),
            "intercept": model.intercept_,
            "r2": r2
        }
    return results
